
#include "graphics/materialmanager.h"
#include "graphics/material.h"

namespace dw
{
	namespace graphics
	{

		MaterialManager::MaterialManager()
		{
		}

		MaterialManager::~MaterialManager()
		{
		}

		Material* MaterialManager::getMaterial(const unsigned i) const
		{
			dwAssert(i < _materials.size(), "Index is out of range");
			
			return _materials[i];
		}

		Material* MaterialManager::getMaterial(const std::string& name)
		{
			MaterialIndexMap::iterator iter = _materialsIndex.find(name);

			if (iter == _materialsIndex.end())
				return 0;
			return getMaterial(iter->second);
		}

		Material* MaterialManager::createMaterial(const std::string& name)
		{
			MaterialIndexIterator iter			= _materialsIndex.find(name);
			Material* material;

			if (iter == _materialsIndex.end())
			{
				material = new Material(name);
				addMaterial(material);
			}
			else
				material = _materials[iter->second];
			return material;
		}

		void MaterialManager::addMaterial(Material* material)
		{
			if (material)
			{
				_materialsIndex.insert(std::make_pair(material->getName(), static_cast< unsigned >(_materials.size())));
				_materials.push_back(material);
			}
		}

		void MaterialManager::removeMaterial(const unsigned i)
		{
			dwAssert(i < _materials.size(), "Index is out of range");

			_materialsIndex.erase(_materials[i]->getName());
			_materials.erase(_materials.begin() + i);
		}

		void MaterialManager::removeMaterial(const std::string& name)
		{
			MaterialIndexMap::const_iterator iter = _materialsIndex.find(name);

			if (iter != _materialsIndex.end())
				removeMaterial(iter->second);
		}

		void MaterialManager::removeMaterial(const Material* material)
		{
			if (material)
				removeMaterial(material->getName());
		}

	} // namespace graphics 
} // namespace dw 